package com.ruoyi.framework.security.handle;

import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * description: 重写框架里面的密码校验器，目的是在单点登录时不匹配密码
 *              原来的方式会匹配两次密码，第二次是在 DaoAuthenticationProvider 中
 * auth fcb
 * date 2025-04-09 16:04
 **/
public class AiShanDongDaoAuthenticationProvider extends DaoAuthenticationProvider {

    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Failed to authenticate since no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            // 如果是爱山东的单点登录则直接放行
            String aiShanDongSSOFlag = (String)authentication.getDetails();
            if(UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG.equals(aiShanDongSSOFlag)) {
                return;
            }
            String presentedPassword = authentication.getCredentials().toString();
            if (!getPasswordEncoder().matches(presentedPassword, userDetails.getPassword())) {
                this.logger.debug("Failed to authenticate since password does not match stored value");
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        }
    }
}
